<!-- 顾客中心-顾客管理 -->
<template>
  <div class="main-content-container">
    <!-- 表单区域 -->
    <div ref="search">
      <el-form ref="searchForm" :model="searchForm" label-width="100px" :inline="true">
        <el-row>
          <!-- <el-col :span="12">
            <el-form label-width="80px" :inline="true">
              <el-form-item>
                <el-input v-model="custQuery" class="inputCss" placeholder="姓名、手机号、会员号" clearable @change="handleChange" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleChange">搜索顾客</el-button>
                <el-button @click="eliminate">清除</el-button>
              </el-form-item>
            </el-form>
          </el-col> -->
          <el-col :span="14" class="searchs-y">
            <el-form ref="searchs" label-width="80px" :inline="true">
              <el-form-item>
                <el-input v-model="custQuery" placeholder="姓名、手机号、会员号" clearable @change="handleChange">
                  <el-button slot="append" icon="el-icon-search" @click="handleChange" />
                </el-input>
                <el-form-item v-if="false" class="spn buttons clear-button">
                  <el-button type="primary" @click="eliminate">清除</el-button>
                </el-form-item>
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="10">
            <el-form-item class="spn buttons">
              <el-button type="primary" @click="addCustomerbBtn">+ 增加顾客</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <span>
            <el-col :span="4.5">
              <el-form-item label="建档时间：" label-width="72px">
                <el-date-picker
                  id="starttime"
                  v-model="timeVlaue"
                  type="daterange"
                  value-format="yyyy-MM-dd"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  class="el-date-picker-y"
                  @change="searchBtn"
                />
              </el-form-item>
            </el-col>
            <el-col :span="4.5">
              <el-form-item>
                <el-select
                  v-model="searchForm.temporarySign"
                  class="el-select-y"
                  clearable
                  placeholder="请选择是否临客"
                  @change="getCustomersList"
                >
                  <el-option label="是" value="是" />
                  <el-option label="否" value="否" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4.5">
              <el-form-item>
                <!-- <dictionary-selector
                code="swan_source"
                clearable
                :value.sync="searchForm.developmentChannels"
                @change="channelChange"
              /> -->
                <!-- <dictionary-selector placeholder="请选择渠道" code="swan_source" class="el-select-y" clearable :value.sync="searchForm.developmentChannels" @change="change" /> -->
                <el-select
                  v-model="searchForm.developmentChannelsId"
                  class="el-select-y"
                  clearable
                  placeholder="请选择来源类型"
                  @change="developmentChannelsChange"
                >
                  <el-option
                    v-for="item in regions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="4.5">
              <el-form-item>
                <el-select
                  v-model="searchForm.channelNameId"
                  class="el-select-y"
                  clearable
                  placeholder="请选择来源名称"
                  @change="getCustomersList"
                >
                  <el-option
                    v-for="item in allChannel"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col> -->
            <el-col :span="4.5">
              <el-form-item>
                <!-- <dictionary-selector code="swan_customer_yxd" :value.sync="searchForm.channelName" @change="searchBtn" /> -->
                <el-select
                  v-model="searchForm.developersId"
                  class="el-select-y"
                  clearable
                  placeholder="请选择开发人员"
                  @change="getCustomersList"
                >
                  <el-option
                    v-for="item in allDeveloper"
                    :key="item.id"
                    :label="item.usrName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4.5">
              <el-form-item>
                <el-select
                  v-model="searchForm.attributionConsultantId"
                  class="el-select-y"
                  clearable
                  placeholder="请选择归属咨询师"
                  @change="change"
                >
                  <el-option
                    v-for="item in attributionConsultantList"
                    :key="item.id"
                    :label="item.usrName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </span>
        </el-row>
      </el-form>
    </div>
    <!-- 表格区域 -->
    <div class="box-show" :style="'height:'+ (innerHeight + 92) + 'px'">
      <el-table v-loading="loading" :data="customersList" border :row-class-name="tableColor" :height="innerHeight">
        <el-table-column label="顾客编号" prop="code" width="160" :show-overflow-tooltip="true" />
        <el-table-column label="名字" prop="name" :show-overflow-tooltip="true" />
        <el-table-column label="手机" prop="phone" :show-overflow-tooltip="true" />
        <el-table-column label="性别" prop="sex" width="50" :show-overflow-tooltip="true" />
        <el-table-column label="年龄" prop="age" width="50" :show-overflow-tooltip="true" />
        <el-table-column label="临客" prop="temporarySign" width="50" :show-overflow-tooltip="true" />
        <el-table-column label="来源类型" prop="developmentChannels" :show-overflow-tooltip="true" />
        <el-table-column label="来源名称/推荐人" prop="channelName" :show-overflow-tooltip="true">
          <template slot-scope="{row}">
            {{ row.developmentChannels === "老带新" || row.developmentChannels === "内推" ? row.recommenderName : row.channelName }}
          </template>
        </el-table-column>
        <el-table-column label="开发人员" prop="developersName" :show-overflow-tooltip="true" />
        <el-table-column label="归属咨询师" prop="attributionConsultantName" :show-overflow-tooltip="true" />
        <el-table-column label="操作" min-width="220">
          <template slot-scope="scope">
            <el-button type="text" @click="detailsBtn(scope.row)">查看详情</el-button>
            <el-button type="text" @click="modifyCustomerbBtn(scope.row)">编辑资料</el-button>
            <el-button type="text" @click="modifyAscription(scope.row)">更改归属</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination :page-num="params.page" :page-size="params.pageSize" :on-change="handlePaginationChange" :total="total" />
    </div>
    <Dialog :title="title" :visible.sync="visibles" :button-text="testBtn" :reveal="show" :width="widths" :loading="loading" class="dialogStyle two-columns" @close="handleCloses">
      <div v-if="!flag">
        <Lable
          ref="label"
          :details="selectCustomersData"
          @modifySuccess="modifySuccess"
          @closeHandle="handleCloses"
          @recharge="recharge"
          @refundBalance="refundBalance"
          @openAdvisoryRecord="openAdvisoryRecord"
          @seeOrderDetails="seeOrderDetails"
          @viewProject="viewProject"
          @viewVisit="viewVisit"
        />
      </div>
    </Dialog>
    <Recharge :visible.sync="visible1" :ids="ids" @cancels="(visible1 = false), (ids = '')" @rechargeSuccess="rechargeSuccess" />
    <RefundBalance :visible.sync="visible2" :ids="ids" @cancels="(visible2 = false), (ids = '')" @rechargeSuccess="rechargeSuccess" />
    <AdvisoryRecord ref="advisoryRecord" :id-list="advisoryIdList" />
    <OrderDetails :visible.sync="orderDetailVisible" :customer-id="customerId" :order-details-id="orderId" @seeDetails="closeOrderDetail" />
    <SeeReturnVisit v-if="visibleVisitDetails" :visible.sync="visibleVisitDetails" :current-row="currentRowVisitDetails" @handleClose="visibleVisitDetails = false" />
    <ProjectDetails ref="projectDetails" :visible.sync="ProjectVisible" :title="ProjectTitle" />
    <Dialogs
      v-if="visible"
      :visible.sync="visible"
      :flag="flag"
      :is-info="isInfo"
      :is-modify="isModify"
      :title="title"
      :current-row="addCustomersData"
      @handleClose="handleClose"
      @handleSuccess="handleSuccess"
    />
  </div>
</template>
<script>
import AdvisoryRecord from "../../lobby/task/record";
import OrderDetails from "../../lobby/orderOpened/orderDetails.vue";
import ProjectDetails from "../../department/center/projectmenu/dialog";
import SeeReturnVisit from "../../returnVisit/seeReturnVisit";
// import { DictionarySelector } from "@rabbit.do/rabbit";
import "@/assets/styles/common.scss";
import Dialog from "@/components/Dialog/index";
import Lable from "./lable";
import Recharge from "./recharge";
import RefundBalance from "./refundBalance";
import Dialogs from "./dialog";
import { tableColor, labelHeigh } from '@/utils/common.js';
export default {
  components: {
    // DictionarySelector,
    Dialog,
    Dialogs,
    Lable,
    Recharge,
    RefundBalance,
    AdvisoryRecord,
    OrderDetails,
    SeeReturnVisit,
    ProjectDetails,
  },
  data() {
    // var validatorPhone = function(rule, value, callback) {
    //   if (!value) {
    //     callback(new Error('请输入手机号'));
    //   } else if (!/^1\d{10}$/.test(value)) {
    //     callback(new Error('手机号格式错误'));
    //   } else {
    //     callback();
    //   }
    // };
    return {
      searchForm: {},
      advisoryIdList: [],
      tableColor,
      innerHeight: null,
      ageList: [
        { id: 0, label: "不限年龄段" },
        { id: 1, label: "18岁以下" },
        { id: 2, label: "18~25" },
        { id: 3, label: "25~30" },
        { id: 4, label: "30~35" },
        { id: 5, label: "35~40" },
        { id: 6, label: "40岁以上" },
      ],
      developmentChannelsList: [
        { id: 0, lebel: "不限渠道" },
        { id: 1, lebel: "直客" },
        { id: 2, lebel: "渠道" },
        { id: 3, lebel: "网电" },
      ],
      attributionConsultantList: [],
      options: [],
      customersList: [],
      params: {
        page: 1,
        pageSize: this.$store.state.commonsettings.maxPageSize,
      },
      total: 0,
      addCustomersData: {}, // 添加数据
      selectCustomersData: {},
      flag: true,
      title: "",
      testBtn: "",
      visible: false,
      show: true,
      widths: 50,
      loading: false,
      timeVlaue: "",
      rules: {},
      basicsInfo: [],
      ascriptionInfo: [],
      featuresInfo: [],
      isUpdate: false,
      isModify: true,
      isInfo: true,
      visibles: false,
      custQuery: "",
      allChannel: [],
      allDeveloper: [],
      visible1: false,
      ids: "",
      visible2: false,
      archivistName: "",
      orderDetailVisible: false,
      orderId: "",
      customerId: "",
      visibleVisitDetails: false,
      currentRowVisitDetails: {},
      ProjectVisible: false,
      ProjectTitle: "项目单详情",
      regions: [],
    };
  },
  created() {
    this.getCustomersList();
    this.attributionConsultant();
    this.archivistName = this.$store.getters.currentUserInfo.usrName;
    if (this.$route.query.isPopup) {
      this.addCustomerbBtn();
      this.$router.push({
        query: {},
      });
    }
    this.getDicoptList();
    this.getAllDeveloper();
    // this.getAllChannel(undefined);
  },
  mounted() {
    this.$nextTick(function() {
      this.innerHeight = labelHeigh(this.$refs.search);
    });
  },
  methods: {
    // 获取来源类型
    getDicoptList() {
      this.$api["networkpower/sourceType/findAll"]().then((res) => {
        if (res.code !== 200) return this.$message.error(res.msg);
        this.regions = res.data;
      });
    },
    async getAllDeveloper() {
      const res = await this.$api["data/hospitalStaff/getAllByJobName"]({ hospitalJobName: "网电人员" });
      if (res.code !== 200) return this.$message.error(res.msg);
      this.allDeveloper = res.data;
    },
    openAdvisoryRecord(row, id, idList) {
      // 咨询记录
      this.advisoryIdList = idList;
      this.$refs.advisoryRecord.loadDetails(row, id);
    },
    seeOrderDetails(orderId, customerId) {
      // 消费记录
      this.orderId = orderId;
      this.customerId = customerId;
      this.orderDetailVisible = true;
    },
    viewProject(row, customerId) {
      // 项目记录
      this.ProjectTitle = "项目单详情";
      this.ProjectVisible = true;
      this.$refs.projectDetails.toViewBtn(row.id);
    },
    viewVisit(row, customerId) {
      // 回访记录
      this.visibleVisitDetails = true;
      this.currentRowVisitDetails = row;
    },
    closeOrderDetail() {
      this.orderDetailVisible = false;
    },
    async attributionConsultant() {
      const res = await this.$api["data/hospitalStaff/getAllByJobName"]({
        hospitalJobName: "咨询师",
      });
      if (res.code !== 200) return;
      this.attributionConsultantList = res.data;
    },
    handleChange() {
      this.params.page = 1;
      this.getCustomersList();
    },
    async getCustomersList() {
      const searchForm = JSON.parse(JSON.stringify(this.searchForm));
      if (!searchForm.age) searchForm.age = undefined;
      if (searchForm.age === "18岁以下") searchForm.age = "0~18";
      if (searchForm.age === "40岁以上") searchForm.age = "40~100";
      if (!searchForm.temporarySign) searchForm.temporarySign = undefined;
      if (searchForm.temporarySign === "临客") searchForm.temporarySign = "是";
      if (searchForm.temporarySign === "正客") searchForm.temporarySign = "否";
      if (!searchForm.developersId) searchForm.developersId = undefined;
      if (!searchForm.developmentChannelsId) {
        searchForm.developmentChannelsId = undefined;
      }
      if (!searchForm.channelNameId) searchForm.channelNameId = undefined;
      if (!searchForm.sex) searchForm.sex = undefined;
      if (!searchForm.temporarySign) searchForm.temporarySign = undefined;
      if (!searchForm.attributionConsultantId) {
        searchForm.attributionConsultantId = undefined;
      }
      this.loading = true;
      const res = await this.$api["customer/customers/list"]({
        ...this.params,
        query: searchForm,
        custQuery: this.custQuery,
      });
      this.loading = false;
      if (res.code !== 200) return this.$message.error("查询顾客列表失败！");
      this.customersList = res.data.result;
      this.total = res.data.total;
    },
    handlePaginationChange(val) {
      this.params = { page: val.pageNum, pageSize: val.pageSize };
      this.getCustomersList();
    },
    handleClose() {
      // this.$refs["from"].clearValidate();
      this.visible = false;
    },
    handleCloses() {
      this.visibles = false;
      this.$refs.label.labelNum = 0;
    },
    // 添加
    addCustomerbBtn() {
      this.title = "新增顾客";
      this.testBtn = "保存";
      this.addCustomersData = {};
      this.flag = true;
      this.visible = true;
      this.isInfo = true;
      this.isModify = true;
    },
    modifyCustomerbBtn(row) {
      this.title = "修改顾客";
      this.testBtn = "保存";
      if (row.attributionConsultantId) {
        row.attributionConsultantId = row.attributionConsultantId.toString();
      }
      if (row.cityCode) {
        const list = row.cityCode.split(",");
        const json = {
          provinceCode: list[0],
          cityCode: list[1] || "",
          regionCode: list[2] || "",
        };
        this.$set(row, "city", json);
        this.isUpdate = true;
      }
      this.addCustomersData = row;
      console.log(this.addCustomersData);
      this.flag = true;
      this.visible = true;
      this.isInfo = false;
      this.isModify = true;
    },
    modifyAscription(row) {
      this.title = "更改归属";
      this.testBtn = "保存";
      this.addCustomersData = row;
      this.flag = true;
      this.visible = true;
      this.isInfo = true;
      this.isModify = false;
    },
    // 搜索
    searchBtn(value) {
      if (value) {
        this.searchForm.createdTime =
          value[0] + " 00:00:00" + "_" + value[1] + " 23:59:59";
      } else {
        this.searchForm.createdTime = undefined;
      }
      this.params.page = 1;
      this.getCustomersList();
    },
    change() {
      this.params.page = 1;
      this.getCustomersList();
    },
    // 详情
    async detailsBtn(row) {
      const res = await this.$api["customer/customers/details"]({ id: row.id });
      if (res.code !== 200) return this.$message.error("查看详情失败！");
      this.selectCustomersData = res.data;
      this.title =
        "查看顾客档案 （" +
        this.selectCustomersData.name +
        " No." +
        this.selectCustomersData.code +
        " )";
      this.show = false;
      this.flag = false;
      this.widths = 70;
      this.visibles = true;
    },
    modifySuccess() {
      this.flag = true;
      this.show = true;
      this.visible = false;
      this.getCustomersList();
    },
    eliminate() {
      this.searchForm = {};
      this.timeVlaue = "";
      this.custQuery = "";
      this.params.page = 1;
      this.getCustomersList();
    },
    recharge() {
      this.visible1 = true;
      this.ids = this.selectCustomersData.id;
    },
    rechargeSuccess() {
      this.detailsBtn(this.selectCustomersData);
    },
    refundBalance() {
      this.visible2 = true;
      this.ids = this.selectCustomersData.id;
    },
    handleSuccess() {
      this.params.page = 1;
      this.getCustomersList();
      this.visible = false;
    },
    developmentChannelsChange(id) {
      // this.$set(this.searchForm, "channelNameId", "");
      // this.getAllChannel(id || undefined);
      this.getCustomersList();
    },
    async getAllChannel(id) {
      const res = await this.$api["customer/customers/getAllSource"]({
        query: { typeId: id },
      });
      if (res.code !== 200) return this.$message.error(res.msg);
      this.allChannel = res.data;
    },
    // 删除
    // deleteBtn(row) {

    // },
  },
};
</script>
<style lang="scss" scoped>
.spn {
  float: right;
  .inputCss {
    width: 248px;
  }
}
.info-title {
  margin: 20px 0;
}
/deep/.el-icon-circle-close.el-select__caret.el-input__icon{
  color: #9baed3 !important;
}
.box-y{
  width: 100%;
}
// 清除按钮
.clear-button button{
  margin-left:10px;
  color:#666666!important;
  margin-top:9px;
}
.clear-button{
  margin-bottom: 0 !important;
}
</style>
